import { defineStore } from 'pinia'
import { ref } from 'vue'
import { toObtainListOfPatientAPI, addOrUpdatePatientAPI, deletePatientAPI, getPatientAPI } from '@/api/patient'
import { ofPatientDataType, responeeOfPatientType, AddOrUpdateUser, responeeOfPatient } from '@/api/patient/type'

export const useClientStore = defineStore('client', () => {
  // 就诊人列表
  const ofPatientList = ref([] as ofPatientDataType[])
  // 就诊人信息
  const ofPatient = ref({} as ofPatientDataType)

  /** 获取就诊人信息 */
  const toObtainListOfPatient = async () => {
    const { data: res }: responeeOfPatientType = await toObtainListOfPatientAPI()
    if (res.code !== 200) return ElMessage.error(res.message)
    ofPatientList.value = res.data
  }
  /** 新增或修改就诊人 */
  const addOrUpdatePatient = async (data: AddOrUpdateUser) => {
    const { data: res } = await addOrUpdatePatientAPI(data)
    if (res.code !== 200) {
      ElMessage.error(res.message)
      return false
    }
    if (data.id) {
      ElMessage.success('添加就诊人成功')
      return true
    } else {
      ElMessage.success('修改就诊人成功')
      return true
    }
  }
  /**删除就诊人
   * @param id { number | string } 就诊人 id
   */
  const deePatient = async (id: string | number) => {
    const { data: res } = await deletePatientAPI(id)
    if (res.code !== 200) return ElMessage.error(res.message)
    ElMessage.success('删除成功')
    toObtainListOfPatient()
  }

  /** 获取就诊人
   * @param id { number | string } 就诊人 id
   */
  const getPatient = async (id: number | string) => {
    const { data: res }: responeeOfPatient = await getPatientAPI(id)
    if (res.code !== 200) return ElMessage.error(res.message)
    ofPatient.value = res.data
  }

  return {
    ofPatientList,
    toObtainListOfPatient,
    addOrUpdatePatient,
    deePatient,
    ofPatient,
    getPatient,
  }
})
